package cn.wolfcode.web.modules.orderinfo.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.wolfcode.web.commons.entity.LayuiPage;
import cn.wolfcode.web.commons.utils.LayuiTools;
import cn.wolfcode.web.commons.utils.PoiExportHelper;
import cn.wolfcode.web.commons.utils.SystemCheckUtils;
import cn.wolfcode.web.modules.BaseController;
import cn.wolfcode.web.modules.custinfo.entity.TbCustomer;
import cn.wolfcode.web.modules.custinfo.service.ITbCustomerService;
import cn.wolfcode.web.modules.linkman.entity.TbCustLinkman;
import cn.wolfcode.web.modules.linkman.mapper.TbCustLinkmanMapper;
import cn.wolfcode.web.modules.linkman.service.ITbCustLinkmanService;
import cn.wolfcode.web.modules.linkmanvisit.entity.TbVisit;
import cn.wolfcode.web.modules.log.LogModules;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.wolfcode.web.modules.orderinfo.entity.TbOrderInfo;
import cn.wolfcode.web.modules.orderinfo.service.ITbOrderInfoService;

import link.ahsj.core.annotations.AddGroup;
import link.ahsj.core.annotations.SameUrlData;
import link.ahsj.core.annotations.SysLog;
import link.ahsj.core.annotations.UpdateGroup;
import link.ahsj.core.entitys.ApiModel;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @author MAOWEI
 * @since 2023-08-01
 */
@Controller
@RequestMapping("orderinfo")
public class TbOrderInfoController extends BaseController {

    @Autowired
    private ITbOrderInfoService entityService;

    @Autowired
    private ITbCustLinkmanService custLinkmanService;

    @Autowired
    private ITbCustomerService customerService;

    private static final String LogModule = "TbOrderInfo";

    @GetMapping("/list.html")
    public ModelAndView list(ModelAndView mv) {
        List<TbCustomer> list = customerService.list();
        mv.addObject("custs", list);
        List<TbCustLinkman> list1 = custLinkmanService.list();
        mv.addObject("linkmen", list);
        mv.setViewName("order/orderinfo/list");
        return mv;
    }

    @RequestMapping("/add.html")
    @PreAuthorize("hasAuthority('order:orderinfo:add')")
    public ModelAndView toAdd(ModelAndView mv) {
        List<TbCustomer> list = customerService.list();
        mv.addObject("custs", list);
        mv.setViewName("order/orderinfo/add");
        return mv;
    }

    @GetMapping("/{id}.html")
    @PreAuthorize("hasAuthority('order:orderinfo:update')")
    public ModelAndView toUpdate(@PathVariable("id") String id, ModelAndView mv) {
        List<TbCustomer> customerList = customerService.list();
        mv.addObject("custs", customerList);
        mv.setViewName("order/orderinfo/update");
        TbOrderInfo orderInfo = entityService.getById(id);
        mv.addObject("obj", orderInfo);

        List<TbCustLinkman> list = custLinkmanService.list(new LambdaQueryWrapper<TbCustLinkman>().eq(TbCustLinkman::getCustId, orderInfo.getCustId()));
        mv.addObject("custLinkManList", list);
        mv.addObject("id", id);
        return mv;
    }

    @RequestMapping("list")
    @PreAuthorize("hasAuthority('order:orderinfo:list')")
    public ResponseEntity page(LayuiPage layuiPage, String delivertime, String receivetime, String custId) {
        SystemCheckUtils.getInstance().checkMaxPage(layuiPage);
        IPage page = new Page<>(layuiPage.getPage(), layuiPage.getLimit());

        page = entityService.lambdaQuery()
                .eq(!StringUtils.isEmpty(custId), TbOrderInfo::getCustId, custId)
                .ge(!StringUtils.isEmpty(delivertime), TbOrderInfo::getDeliverTime, delivertime)
                .le(!StringUtils.isEmpty(receivetime), TbOrderInfo::getReceiveTime, receivetime)
                .page(page);

        List<TbOrderInfo> records = page.getRecords();
        for (TbOrderInfo record : records) {
            TbCustomer tbCustomer = customerService.getById(record.getCustId());
            record.setCustName(tbCustomer.getCustomerName());

            TbCustLinkman linkman = custLinkmanService.getById(record.getReceiver());
            System.out.println(linkman);
            record.setReceiverName(linkman.getLinkman());
        }
        return ResponseEntity.ok(LayuiTools.toLayuiTableModel(page));
    }

    @SameUrlData
    @PostMapping("save")
    @SysLog(value = LogModules.SAVE, module = LogModule)
    @PreAuthorize("hasAuthority('order:orderinfo:add')")
    public ResponseEntity<ApiModel> save(@Validated({AddGroup.class}) @RequestBody TbOrderInfo entity) {
        entityService.save(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SameUrlData
    @SysLog(value = LogModules.UPDATE, module = LogModule)
    @PutMapping("update")
    @PreAuthorize("hasAuthority('order:orderinfo:update')")
    public ResponseEntity<ApiModel> update(@Validated({UpdateGroup.class}) @RequestBody TbOrderInfo entity) {
        entityService.updateById(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SysLog(value = LogModules.DELETE, module = LogModule)
    @DeleteMapping("delete/{id}")
    @PreAuthorize("hasAuthority('order:orderinfo:delete')")
    public ResponseEntity<ApiModel> delete(@PathVariable("id") String id) {
        entityService.removeById(id);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SysLog(value = LogModules.DELETE, module = LogModule)
    @RequestMapping("export")
    public void export(String custId, HttpServletResponse response) {
        List<TbOrderInfo> list = entityService.lambdaQuery()
                .eq(!StringUtils.isEmpty(custId), TbOrderInfo::getCustId, custId)
                .list();

        ExportParams exportParams = new ExportParams();
        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, TbOrderInfo.class, list);
        try {
            PoiExportHelper.exportExcel(response, "订单表", sheets);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}
